package com.web.webth.controller;

import com.alibaba.fastjson.JSON;
import com.web.webth.mq.BaseMsg;
import com.web.webth.pojo.AuthUser;
import com.web.webth.service.AuthUserService;
import com.web.webth.utils.KeyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * Created with IDEA
 * author:HanLiBin
 * Date:2018/3/2
 * Time:9:59
 * version 1.0
 */
@Controller
public class AuthUserController {
    @Autowired
    private AuthUserService authUserService;
    @Autowired
    private JmsTemplate jmsTemplate;
    @GetMapping("/")
    public String index (Map map) {
        List<AuthUser> users=authUserService.findAll();
        map.put("users",users);
        return "index";
    }
    @PostMapping("save")
    public String save( AuthUser authUser){
        if(authUser!=null){
            authUserService.create(authUser);
        }
        return "redirect:/";
    }
    @PostMapping("send")
    public void send(Integer userid, HttpServletResponse response){
        byte[] encryptdata = null;
        try {
            if (!StringUtils.isEmpty(userid)) {
                AuthUser authUser = authUserService.findById(userid);
                String data = JSON.toJSONString(authUser);
                encryptdata = KeyUtils.encryptByPublicKey(data);
                jmsTemplate.send("my_destination", new BaseMsg(encryptdata));
                response.getWriter().write("ok");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
